<template>
  <el-scrollbar height="100%">
    <ContentWrap v-loading="formLoading">
      <div class="page-title"><span>{{ previousRouterName }}</span>
        {{ pageType === 'create' ? '新建' : pageType === 'update' ? '编辑' : '详情'}}</div>
      <div class="render-container">
          <v-form-render v-if="formJson" :form-json="formJson" :disabled="pageType == 'detail'" ref="vFormRef" :render-config="configData" />
          <div class="btn-box">
            <el-button type="primary" @click="submitForm" v-if="pageType != 'detail'">确定</el-button>
            <el-button type="default" @click="cancelClick">取消</el-button>
          </div>
        </div>
      </ContentWrap>
  </el-scrollbar>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { InstanceApi } from '@/api/infra/instance/index'
import { containsArray, isNumeric } from '../utils'
import { routePrefix, formNamePrefix, uploadData } from '../config'
const router = useRouter()
defineOptions({ name: 'Render' })
const previousRouterPath: any = ref('')
const pageType: any = ref('create')
const formJson = ref()
const formCodeStr: any = ref('')
const vFormRef: any = ref(null)
const detailId: any = ref(undefined)
// 提交接口
const submitForm = () => {
  vFormRef.value
    .getFormData()
    .then(async (formData) => {
      // Form Validation OK
      var params: any = {
        data: formData,
        formCode: formCodeStr.value
      }
      console.log(formData, 'formData')
      if (pageType.value === 'create') {
        await InstanceApi.createInstance(params)
        ElMessage.success('添加成功')
        backRouter(previousRouterPath.value)
      } else {
        params.id = Number(detailId.value)
        params.data.id = Number(detailId.value)
        await InstanceApi.updateInstance(params)
        ElMessage.success('编辑成功')
        backRouter(previousRouterPath.value)
      }
    })
    .catch((error) => {
      // Form Validation failed
      ElMessage.error(error)
    })
}
const cancelClick = () => {
  backRouter(previousRouterPath.value)
}
// 获取json数据
const getJSonData = async (formCode) => {
  formLoading.value = true
  try {
    let res = await InstanceApi.getInstanceData({ formCode })
    formJson.value = JSON.parse(res)
    formLoading.value = false
  } finally {
    formLoading.value = false
  }

}
const formLoading = ref(false)
// 详情接口
const getDetailData = async (formCode) => {
  try {
    let res = await InstanceApi.instanceDetail({ formCode, id: detailId.value })
    var uploadFilter = [] as string[]
    formJson.value.widgetList.filter((item: any) => {
      if (uploadData.includes(item.type)) {
        uploadFilter.push(item.options.name)
      } 
    })
    var params: any = {}
    for (var key in res) {
      // 检测接口内为id的参数转换成数字
      if (isNumeric(res[key])) {
        res[key] = Number(res[key])
      }
      // 检测接口内字符串含有数组的转换为数组
      if (typeof res[key] === 'string') { 
        if (containsArray(res[key])) { 
          res[key] = JSON.parse(res[key])
        }
      }
      // 检测为上传组件的字段由null转换成数组
     if (uploadFilter.includes(key))  {
      // 如果不是数组就置为数组
      if (!Array.isArray(res[key])) {
        res[key] = []
      }
      
     }
      params[key] = res[key]
    }
    // 设置FormData
    vFormRef.value.setFormData(params)
    } finally {
    }
  
}
const backRouter = (path: string) => {
  router.push({
    path: path
  })
}
// 传给v-form的参数，目前只有上传组件需要
const configData = ref({
  upload_data: {
    businessField: ''
  }
})
// 上一个页面的路由
const previousRouterName = ref()
onMounted( () => {
  var routerObj = router.currentRoute.value
  var formCode = routerObj.query.formCode
  detailId.value = routerObj.query.id
  pageType.value = routerObj.query.type
  previousRouterName.value = routerObj.query.currentRouteName
  // previousRouterPath.value = `${routePrefix}${formCode}`
  previousRouterPath.value = routerObj.query.currentRoutePath
  configData.value.upload_data.businessField = `${formNamePrefix}${formCode}`
  
  if (formCode) {
    getJSonData(formCode)
    formCodeStr.value = formCode
  }
  if (detailId.value) {
    // 使用定时器加载vform3
   var timer = setInterval(() => {
    if (vFormRef.value != null) {
      getDetailData(formCode)
      clearInterval(timer)
    }
   })
  }
})
</script>

<style lang="scss" scoped>
.btn-box {
  display: flex;
  justify-content: center;
  margin: 40px 0;
}

.render-container{
  width: 100%;
  height: 100%;
}

.page-title {
  padding-bottom: 20px;
  font-size: 16px;
  text-align: center;
  
  span {
    font-size: 18px;
    font-weight: 500;
  }
}

</style>
